package com.example.stock.tencent;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import com.example.stock.entity.StockDataResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author tanlvxu
 * @Date 2024/12/18 17:28
 * @Description 腾讯接口调用
 */
@Component
public class TencentProxy {

    @Autowired
    private ResourceLoader resourceLoader;

    public List<StockBean> getDataByCodes(String codes)  {
        try {
            String result = HttpClientPool.getHttpClient().get("http://qt.gtimg.cn/q=" + codes);
            return parse(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public StockDataResponse getStockDataByCode(String code) {
        try {
            String result = HttpClientPool.getHttpClient().get("https://proxy.finance.qq.com/ifzqgtimg/appstock/app/stockinfo/plateNew?app=wzq&zdf=1&code=" + code);
            return JSONUtil.toBean(result, StockDataResponse.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public List<StockBean> getData(){
        List<String[]> data = new ArrayList<>();
        Resource resource = resourceLoader.getResource("classpath:all_stock.csv");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",");
                data.add(fields);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        data.remove(0);
        // 使用Hutool的分组方法
        List<List<String[]>> groupedArray = CollUtil.split(data, 100);
        StringBuilder builder = new StringBuilder();
        // 输出分组后的结果
        int index = 1;
        for (List<String[]> group : groupedArray) {
            String urlPara = group.stream().map(o -> o[0].replace(".", "")).collect(Collectors.joining(","));
            try {
                Console.log(String.format("当前请求第%d组,一共%d组",index++, groupedArray.size()));
                String result = HttpClientPool.getHttpClient().get("http://qt.gtimg.cn/q=" + urlPara);
                builder.append(result);
                Thread.sleep(10);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return parse(builder.toString());
    }

    private HashMap<String, String[]> codeMap = new HashMap<>();

    private List<StockBean> parse(String result) {
        List<StockBean> resultArr = new ArrayList<>();
        String[] lines = result.split("\n");
        for (String line : lines) {
            String code = line.substring(line.indexOf("_") + 1, line.indexOf("="));
            String dataStr = line.substring(line.indexOf("=") + 2, line.length() - 2);
            String[] values = dataStr.split("~");
            StockBean bean = new StockBean(code, codeMap);
            bean.setName(values[1]); //名称
            bean.setPriceNow(NumUtil.change(values[3])); //现价
            bean.setPriceChange(NumUtil.change(values[31])); //涨跌
            bean.setChangePercent(NumUtil.change(values[32])); //涨跌%
            bean.setCalcTime(values[30]); //时间
            bean.setPriceMax(NumUtil.change(values[33]));//最高
            bean.setPriceMin(NumUtil.change(values[34]));//最低
            bean.setPriceAvg(NumUtil.change(values[51]));//均价
            bean.setVolume(Long.parseLong(values[6])); //成交量
            bean.setOutPan(Long.parseLong(values[7])); //外盘
            bean.setInPan(Long.parseLong(values[8]));  //内盘
            bean.setTurnover(NumUtil.change(values[57])); //成交额
            StockBean.OrderBook buyOrderBook = new StockBean.OrderBook();
            List<StockBean.Order> buyOrders = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                StockBean.Order order = new StockBean.Order(NumUtil.change(values[9 + i * 2]), Integer.parseInt(values[9 + i * 2 + 1]));
                buyOrders.add(order);
            }
            buyOrderBook.setOrders(buyOrders);
            bean.setBuyOrders(buyOrderBook);

            StockBean.OrderBook saleOrderBook = new StockBean.OrderBook();
            List<StockBean.Order> saleOrders = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                StockBean.Order order = new StockBean.Order(NumUtil.change(values[19 + i * 2]), Integer.parseInt(values[19 + i * 2 + 1]));
                saleOrders.add(order);
            }
            saleOrderBook.setOrders(saleOrders);
            bean.setSellOrders(saleOrderBook);

            bean.setAmplitude(NumUtil.change(values[43])); //振幅
            bean.setPeRatioTTM(NumUtil.change(values[39])); //市盈率
            bean.setPeRatio(NumUtil.change(values[46]));  //市净率
            bean.setTotalMarketCap(NumUtil.change(values[45]));   // 总市值（亿元）
            bean.setCirculatingCap(NumUtil.change(values[44]));   // 流通市值（亿元）
            bean.setDynamicPeRatio(NumUtil.change(values[52])); //动态市盈率
            bean.setStaticPeRatio(NumUtil.change(values[53])); //静态市盈率
            bean.setVolumeCompare(NumUtil.change(values[49])); //量比
            bean.setExchange(NumUtil.change(values[38])); //换手
            bean.setHighLimit(NumUtil.change(values[47])); //涨停价
            bean.setLowLimit(NumUtil.change(values[48])); //跌停价

            BigDecimal now = new BigDecimal(values[3]);
            String costPriceStr = bean.getCostPrise();
            if (StringUtils.isNotEmpty(costPriceStr)) {
                BigDecimal costPriceDec = new BigDecimal(costPriceStr);
                BigDecimal incomeDiff = now.add(costPriceDec.negate());
                if (costPriceDec.compareTo(BigDecimal.ZERO) <= 0) {
                    bean.setIncomePercent("0");
                } else {
                    BigDecimal incomePercentDec = incomeDiff.divide(costPriceDec, 5, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.TEN)
                            .multiply(BigDecimal.TEN)
                            .setScale(3, RoundingMode.HALF_UP);
                    bean.setIncomePercent(incomePercentDec.toString());
                }

                String bondStr = bean.getBonds();
                if (StringUtils.isNotEmpty(bondStr)) {
                    BigDecimal bondDec = new BigDecimal(bondStr);
                    BigDecimal incomeDec = incomeDiff.multiply(bondDec)
                            .setScale(2, RoundingMode.HALF_UP);
                    bean.setIncome(incomeDec.toString());
                }
            }

            resultArr.add(bean);
        }
        return resultArr;
    }
}
